package com.engine.jucailinkq.attendance.attendanceanalysis.thread;

import com.engine.common.util.ServiceUtil;
import com.engine.jucailinkq.attendance.attendanceanalysis.service.UtilService;
import com.engine.jucailinkq.attendance.attendanceanalysis.service.impl.UtilServiceImpl;
import com.engine.jucailinkq.attendance.attendanceanalysis.wrapper.AttendanceAnalysisWrapper;
import com.engine.jucailinkq.attendance.attendanceplan.service.AttendancePlanService;
import com.engine.jucailinkq.attendance.attendanceplan.service.impl.AttendancePlanServiceImpl;
import com.engine.jucailinkq.attendance.workflow.service.AllowanceService;
import com.engine.jucailinkq.attendance.workflow.service.impl.AllowanceServiceImpl;
import com.engine.jucailinkq.common.util.DateUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;

import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @version 1.0
 * @Title ecology-9
 * @Company 泛微软件
 * @CreateDate 2024/10/9
 * @Description
 * @Author AdminZm
 */
public class AttendanceAnalysisJobThread extends BaseBean implements Runnable{

    private Map<String,Object> userMap;

    private Map<String,Object> departEmployeeMap;

    private Map<String, List<Map<String,Object>>> collect;

    private Map<String,List<Map<String,Object>>> attendaceGroupById;

    private Map<String, Object> attendanceCycle;
    private String useDate;

    private AttendancePlanService basicsetService = ServiceUtil.getService(AttendancePlanServiceImpl.class);

    private AttendanceAnalysisWrapper attendanceAnalysisService = ServiceUtil.getService(AttendanceAnalysisWrapper.class);


    public AttendanceAnalysisJobThread(Map<String,Object> userMap, Map<String,Object> departEmployeeMap,
                                       Map<String, List<Map<String,Object>>> collect, Map<String,List<Map<String,Object>>> attendaceGroupById,
                                       Map<String,Object> attendanceCycle, String useDate) {
        this.userMap = userMap;
        this.departEmployeeMap = departEmployeeMap;
        this.collect = collect;
        this.attendaceGroupById = attendaceGroupById;
        this.attendanceCycle = attendanceCycle;
        this.useDate = useDate;
    }

    @Override
    public void run() {
        String userId = Util.null2String(userMap.get("id"));
        writeLog("AttendanceAnalysisJobThread start:" + userId);
        //入职日期
        String companystartDate = Util.null2String(userMap.get("companystartdate"));

        //离职日期
        String terminationDate = Util.null2String(departEmployeeMap.get(userId));

        List<String> analysisDateListOld = Lists.newArrayList((Set<String>) attendanceCycle.get(userId));
        if (CollectionUtils.isEmpty(analysisDateListOld)) {
            return;
        }
        RecordSet rs = new RecordSet();
        List<String> analysisDateList = new ArrayList<>();
        for (String date : analysisDateListOld) {
            if (("".equals(companystartDate) || DateUtil.getTime(date).compareTo(DateUtil.getTime(companystartDate)) > 0)
                    && ("".equals(terminationDate) || DateUtil.getTime(date).compareTo(DateUtil.getTime(terminationDate)) < 0)) {
                analysisDateList.add(date);
            }

            // 入职日期及之前、离职日期及之后的数据逻辑删除
            if ((StringUtils.isNotEmpty(companystartDate) && DateUtil.getTime(date).compareTo(DateUtil.getTime(companystartDate)) <= 0)
                    || (StringUtils.isNotEmpty(terminationDate) && DateUtil.getTime(date).compareTo(DateUtil.getTime(terminationDate)) >= 0)) {
                rs.executeUpdate("UPDATE uf_jcl_kq_cqjg SET sfsc = 1 WHERE ygid = ? AND rq = ?", userId, date);
            }
        }
        if (CollectionUtils.isEmpty(analysisDateList)) {
            return;
        }

        try {
            analysisDateList = analysisDateList.stream().filter(e -> "".equals(companystartDate) || DateUtil.getTime(e).compareTo(DateUtil.getTime(companystartDate)) >= 0).sorted(Comparator.comparing(e -> DateUtil.getTime(e).toInstant(ZoneOffset.of("+8")).toEpochMilli())).collect(Collectors.toList());
            //日期对应的打卡数据
            Map<String, Map<String, Object>> clockInTimeMap = Maps.newHashMap();
            List<String> finalAnalysisDateList = analysisDateList;
            /**获得人员考勤项目*/
            Map<String, Object> paramMap = Maps.newHashMap();
            paramMap.put("startDate", DateUtil.beforeDay(useDate, 1));
            paramMap.put("endDate", DateUtil.beforeDay(useDate, 1));
            paramMap.put("resourceId", userId);
            Map<String, Object> dataMap = basicsetService.getAttendanceItemsByPerson(paramMap);
            List<Map<String, Object>> attendanceItems = (List<Map<String, Object>>) dataMap.get("data");
            /**
             *获得人员综合工时
             */
            Map<String, Object> workHourdataMap = basicsetService.getWorkHoursItemByPerson(paramMap);
            List<Map<String, Object>> workHourItems = (List<Map<String, Object>>) workHourdataMap.get("data");

            Map<String, List<Map<String, Object>>> attendaceResultMap = Maps.newHashMap();
            List<Map<String, Object>> attendaceResultByUser = attendaceGroupById.get(userId);
            if (attendaceResultByUser != null && attendaceResultByUser.size() > 0) {
                attendaceResultMap = attendaceResultByUser.stream().collect(Collectors.groupingBy(e -> e.get("rq").toString()));
            }
            Map<String, List<Map<String, Object>>> finalAttendaceResultMap = attendaceResultMap;
            attendanceAnalysisService.attendanceAnalysis(userId, finalAnalysisDateList, collect.get(userMap.get("id")), attendanceItems, workHourItems, clockInTimeMap, finalAttendaceResultMap);
        } catch (Exception e) {
            writeLog("AttendanceAnalysisJobThread error :" + e);
        }
    }
}
